<template>
  <view class="wrapper">
    <view class="nav" :style="{paddingTop: statusbarHeight + 'px'}">
      <view class="title">
        <view class="back" @click="back" v-if="false">
          <u-icon name="arrow-left" color="#333" size="18px"></u-icon>
        </view>
        <text class="text">商品管理</text>
      </view>
      <view class="tab">
        <u-subsection
            mode="subsection"
            bgColor="#f7f8f9"
            inactiveColor="#666666"
            activeColor="#ff0000"
            :list="tabs"
            @change="changeIndex"
            :current="current"
            fontSize="24rpx"></u-subsection>
      </view>
      <view class="search" v-if="current === 0">
        <u-search
            placeholder="请输入关键字"
            v-model="keyword"
            height="60rpx"
            searchIconSize="50rpx"
            @search="onSearch"
            @custom="onSearch"
        ></u-search>
      </view>
      <view class="create" v-if="!showPop">
        <u-button type="primary" :text="current === 0 ? '添加商品': '添加分类'" size="small" @click="create"></u-button>
      </view>
    </view>
    <u-loading-icon text="加载中" mode="circle" :vertical="true" textSize="24" v-if="loading" />
    <view class="list" v-if="!showPop && list.length > 0">
      <template v-if="current === 1">
        <view class="item category" v-for="(item, index) in list" :key="index" @click="handleCategory(item)">
          <view class="name">
            {{ item.name }}
          </view>
          <view class="children" v-if="item.children && item.children.length > 0">
            <view class="c" v-for="(o, i) in item.children" :key="i" @click.stop="handleCategory(o)">
              {{ o.name }}
            </view>
          </view>
        </view>
      </template>
      <template v-if="current === 0">
        <view class="item product" v-for="(item, index) in list" :key="index" @click="handleProduct(item)">
          <view class="image">
            <u--image
                class="img"
                lazy-load width="160rpx"
                height="160rpx"
                :fade="true" duration="450"
                :src="baseUrl + item.mainImage.path"
                v-if="item.mainImage"></u--image>
          </view>
          <view class="desc">
            <view class="title two-lines">{{ item.title }}</view>
            <view class="price">
              价格: <text class="unit">￥</text><text>{{ item.price * 1 }}</text>
            </view>
          </view>
        </view>
      </template>
    </view>
    <view class="list nothing" v-else>
      暂无相关信息...
    </view>
    <!--<arrow />-->
    <u-back-top bottom="150" right="40" :scroll-top="scrollTop" icon="arrow-up" :customStyle="{'opacity': '0.99'}"></u-back-top>
    <u-popup :show="showPop" @close="closePop" mode="right" :zIndex="999999">
      <!-- 这里个一个v-if, 解决小程序中生命周期bug -->
      <view class="edit" :closeable="true" v-if="showPop">
        <view class="close">
          <u-icon name="close" @click="showPop = false"></u-icon>
        </view>
        <product :item="whichProduct" @submit="submit" @delete="removeProduct" v-if="current === 0" />
        <category :item="whichCategory" :parent="firstCategoryList" @submit="submit" @delete="removeCategory" v-if="current === 1" />
      </view>
    </u-popup>
  </view>
</template>

<script>
// import Arrow from '../../components/arrow'
import Product from './components/Product'
import Category from './components/Category'
import config from '../../config/config'
import base64 from '../../util/base64'
import Supplier from '../../api/supplier'
const model = new Supplier()

export default {
  components: {
    // Arrow,
    Category,
    Product,
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  computed: {
  },
  data() {
    return {
      scrollTop: 0,
      baseUrl: config.baseUrl,
      tabs: ['商品管理', '分类管理'],
      current: 0,
      list: [],
      queryList: {
        page: 0,
        pageSize: 10,
        busy: false
      },
      statusbarHeight: 0,
      keyword: '',
      loading: false,
      showPop: false,
      whichProduct: {},
      whichCategory: {},
      firstCategoryList: []
    }
  },
  onPullDownRefresh() {
    this.queryList = {
      page: 0,
      pageSize: 10,
      busy: false
    }
    this.getList()
  },
  onReachBottom() {
    this.getList(true)
  },
  onLoad(options) {
    // 状态栏高度
    uni.getSystemInfo({
      success: res => {
        this.statusbarHeight = res.statusBarHeight
      }
    })
    // 测试中, Mini => 20px, Android => 32px
    // console.log(this.statusbarHeight)
    const index = +options.type || 0
    this.current = index
    // this.getList()
  },
  onShow() {
    // 登录后退
    this.changeIndex(this.current)
  },
  methods: {
    back() {
      uni.navigateBack()
    },
    changeIndex(index = 0) {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      this.current = index
      this.queryList = {
        page: 0,
        pageSize: 10,
        busy: false
      }
      this.list = []
      this.getList()
    },
    getList(append = false) {
      if (this.current === 0) {
        this.getProduct(append)
      } else {
        this.getCategory().then(() => {
          uni.stopPullDownRefresh();
        })
      }
    },
    getCategory() {
      return new Promise(resolve => {
        this.loading = true
        model.getCategory().then(response => {
          const { data } = response
          // console.log(data)
          this.list = data
          this.firstCategoryList = [...data]
          // 父级名称显示
          const getName = (id) => {
            let name = ''
            this.firstCategoryList.forEach(x => {
              if (x.id === id) {
                name = x.name
              }
            })
            return name
          }
          this.list.forEach(x => {
            if (x.children) {
              x.children.forEach(y => {
                this.$set(y, 'parent', getName(y.parent_id))
              })
            }
          })
          // console.log(this.list)
          resolve()
        }).finally(() => {
          this.loading = false
        })
      })
    },
    getProduct(append) {
      return new Promise(resolve => {
        if (this.queryList.busy === false) {
          this.queryList.page++
          this.queryList.busy = true
          this.loading = true
          model.getProduct({
            ...this.queryList,
            title: this.keyword
          }).then(response => {
            const { data } = response
            // console.log(data)
            if (data.list.length === 0) {
              this.queryList.busy = true
            } else {
              this.queryList.busy = false
              if (append) {
                this.list = this.list.concat(data.list)
              } else {
                this.list = data.list
              }
            }
            resolve()
          }).finally(() => {
            this.loading = false
          })
        } else {
          resolve()
        }
      })
    },
    handleCategory(item) {
      // console.log(item.id)
      this.whichCategory = item
      this.showPop = true
    },
    handleProduct(item) {
      // console.log(item.id)
      // console.log(item)

      // property
      let property = []
      if (item.properties) {
        property = [...item.properties]
      }
      this.$set(item, 'property', property)

      // image
      if (item.image && Array.isArray(item.image) && item.image[0] && item.image[0].image) {
        let image = []
        image = item.image.map(x => x.image)
        if (item.mainImage) {
          image = image.filter(x => x.id !== item.mainImage.id)
          image = [item.mainImage, ...image]
        }
        this.$set(item, 'image', image)
      }
      // console.log(item)

      // sku
      let sku = []
      if (item.skuName) {
        item.skuName.forEach(x => {
          const item = {
            id: x.id,
            name: x.name,
            value: []
          }
          if (x.values) {
            x.values.forEach(y => {
              if (y.value) {
                item.value.push({ v: y.value, id: y.id })
              }
            })
          }
          sku.push(item)
        })
      }
      this.$set(item, 'sku', sku)

      // console.log(item)

      this.whichProduct = item
      this.showPop = true
    },
    onSearch(e) {
      // console.log(e)
      this.queryList = {
        page: 0,
        pageSize: 10,
        busy: false
      }
      this.list = []
      this.getProduct(false)
    },
    closePop() {
      this.showPop = false
      this.whichCategory = {}
      this.whichProduct = {}
    },
    create() {
      this.showPop = true
      this.whichCategory = {
        id: 0,
        parent: '',
        parent_id: 0,
        sort: 0,
        name: ''
      }
      this.whichProduct = {
        id: 0,
        buy_quantity: 1,
        sn: '',
        price: 0,
        title: '',
        stock: 10000,
        image: [],
      }
    },
    submit() {
      this.showPop = false
      this.changeIndex(this.current)
    },
    removeCategory(id) {
      this.showPop = false
      uni.showModal({
        title: '您确定要删除吗?',
        success: res => {
          if (res.confirm) {
            model.removeCategory({ id }).then(() => {
              uni.showToast({
                icon: 'none',
                title: '操作成功'
              })
              setTimeout(() => {
                this.changeIndex(this.current)
              })
            })
          }
        }
      })
    },
    removeProduct(id) {
      this.showPop = false
      uni.showModal({
        title: '您确定要删除吗?',
        success: res => {
          if (res.confirm) {
            model.removeProduct({ id }).then(() => {
              uni.showToast({
                icon: 'none',
                title: '操作成功'
              })
              setTimeout(() => {
                this.changeIndex(this.current)
              })
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  background: $background_color;
  padding-bottom: 100px;
  .search {
    padding: 10rpx 20rpx;
  }
  .nav {
    z-index: 99999;
    position: sticky;
    top: 0;
    background: white;
    .title {
      height: 44px;
      background: white;
      display: flex;
      align-items: center;
      .back {
        width: 44px;
        display: flex;
        justify-content: center;
      }
      .text {
        flex: 1;
        text-align: center;
        font-weight: 700;
        //margin-left: -44px;
      }
    }
    .tab {
      background: white;
      height: 35px;
      padding: 5px 10px;
      position: sticky;
      top: 0;
    }
    .create {
      padding: 20rpx;
      width: 200rpx;
    }
  }
  .list {
    margin: 20rpx;
    min-height: 100px;
    //padding: 20rpx;
    //background: white;
    font-size: 24rpx;
    //border-radius: 10rpx;
    .item {
      background: white;
      padding: 20rpx;
      border-radius: 10rpx;
      margin-bottom: 10px;
      &.category {
        .name {
          font-weight: 700;
          height: 40px;
          line-height: 40px;
        }
        .children {
          //margin-left: 50rpx;
          //background: red;
          .c {
            padding: 0 50rpx;
            height: 40px;
            line-height: 40px;
            border-bottom: 1rpx solid #f3f5f7;
            &:last-child {
              border: none;
            }
          }
        }
      }
      &.product {
        display: flex;
        align-items: center;
        .desc {
          padding-left: 20rpx;
          view {
            height: 30px;
            &.title {
              font-weight: 700;
            }
            &.price {
              color: red;
              font-size: 30rpx;
              font-weight: 700;
            }
          }
        }
      }
    }
  }
  .nothing {
    color: #ccc;
    line-height: 100px;
    background: white;
    text-align: center;
    min-height: 500px;
  }
  .edit {
    width: 700rpx;
    //height: 100vh;
    background: $background_color;
    box-sizing: border-box;
    padding: 20px;
    font-size: 24rpx;
    padding-top: 80px;
    .close {
      height: 30px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
